/**
* @desc A thickbox like plug-in that is designed for web/text content.  Part of the Codereck Javascript Suite.
*
* @copyright Ryan Zec 2007-2009, All Right Reserved
*
* FUCTIONALITY NOTES
* - when using inline content, you can only use that inline content for 1 fade box (so you can't have multiple fade boxes use content with the same content id)
* - while the initial link for a lock_box fade box can be inline, that rest of them are all automatically treated as ajax
* -
* -
* -
* -
* -
* -
* -
* -
*
* @license BSD (see LICENSE file included, the generic templete can be found at http://www.opensource.org/licenses/bsd-license.php)
*/
;(function($)
{
	//create the codereck scope
	$.cr = $.cr || {};

    $.create_fade_box = function(type, wrapper_id, title, content, options)
    {
        var link_id = wrapper_id + '_link';
        var content_id = wrapper_id + '_content';
        var url = content;

        if($('#' + wrapper_id).length == 0)
        {
            $('body').append('<div id="' + wrapper_id + '" class="hide"></div>');

            var html = '<a id="' + link_id + '" href="#" title="' + title + '"></a>';
            $('#' + wrapper_id).append(html);

            if(type == 'ajax')
            {
                $('#' + link_id).addClass('cr_fade_box_ajax');
            }
            else if(type == 'id')
            {
                $('#' + link_id).attr('href', content);
            }
            else
            {
                $('#' + link_id).attr('href', wrapper_id + '_content');
                url = 'manual_cr_fade_box_content';
                html = '<div id="' + content_id + '">' + content + '</div>';
                $('#' + wrapper_id).append(html);
            }

            var options = $.extend(options,
            {
                url: url
            });

            $('#' + link_id).fade_box(options);
        }

        $('#' + link_id).trigger('click');
    }

	//initialization of codereck tabs
	$.fn.fade_box = function(options, show_content)
	{
		if(show_content !== false)
		{
			show_content = true;
		}

		//add code here
		var fade_box = new $.cr.fade_box(this, options, show_content);
	}

	//codereck tab class
	$.cr.fade_box = function(element, options, show_content)
	{
		this.element = element;
		this.element_id = this.element.attr('id');
		this.options = $.extend(
		{
			id: null,
	        width: 50,
	        height: 50,
	        max_width: 800,
	        max_height: 600,
	        link_attribute: 'href',
	        enable_fade: true,
	        fade_click_close: true,
	        fade_width: null,
	        fade_heigth: null,
	        auto_scroll: true,
	        corners: false,
	        color_class: 'black_60',
	        wrapping_class: null,
	        show_title: true,
	        block_ui: true,
	        original: true,

	        /*setting this to true will convert all links in the fade box content to be fade box links to the current
	        fade box.  All locked content links become ajax fade box links*/
	        lock_box: false,
	        lock_box_auto_resize: true,

	        /*adding for internal use along with the lock_box but can be used to have more than 1 link control the
	        same fade box*/
	        target_fade_box: null
		},options);

	    $(this.element).data($.cr.fade_box.instance_key, this);

		this.setup(show_content);
	}

    $.each(['hide_fade', 'show_content', 'update_data', 'show_fade'], function(i, method) {
        $.fn[method] = function() {
            var args = arguments;
			return this.each(function()
			{
	            var instance = $(this).data($.cr.fade_box.instance_key);
	            instance[method].apply(instance, args);
			});
        }
    });

	$.cr.fade_box.instance_key = 'cr_fade_box_instance';
    $.cr.fade_box.get_instance = function(element)
    {
        return $(element).data($.cr.fade_box.instance_key);
    };

    $.extend($.cr.fade_box.prototype, $.cr.core);
	$.extend($.cr.fade_box.prototype,
	{
		setup: function(show_content)
		{
			var self = this;
			var id_is_target = false;

			if(self.options.id == null)
			{
				id_is_target = true;
			}

		    self.options.url = self.element.attr(self.options.link_attribute);
			self.options.id = self.options.id || self.generate_id('cr_fade_box_wrap');
			self.options.target_fade_box = self.options.target_fade_box || self.options.id;

			if(self.options.target_fade_box === self.options.id)
			{
				/*pull the fade box content out of the html and attach it to the fade element with .data() so that if they
				use the lock content option, we will always have the original content available*/
				if(!this.element.hasClass('cr_fade_box_ajax'))
				{
					var inline_content = $('#' + self.options.url).clone(true);
					$('#' + self.options.url).remove();
					$(self.element).data('cr_fade_box_content', inline_content);
				}

	            //declaring these variable reduce size when mining the js
				var dim_class = 'cr_fade_box_dim';
				var content_class = 'cr_fade_box_content';
				var loading_class = 'cr_fade_box_loading';

				$('body').append('<div id="' + self.options.id + '"></div>');

				//create required divs
        		$('#' + self.options.id).append('<div class="' + dim_class + ' ' + self.options.color_class + '"></div>');
			    $('#' + self.options.id).append('<div class="' + content_class + '"></div>');
			    $('#' + self.options.id + ' .' + content_class).append('<div class="cr_content"></div>');
		        $('#' + self.options.id).append('<div class="' + loading_class + '"></div>');

		        //hide all divs
		        $('#' + self.options.id + ' .' + loading_class).hide();
		        $('#' + self.options.id + ' .' + content_class).hide();
		        $('#' + self.options.id + ' .' + dim_class).hide();

		        //Not sure exactly why this was here but removing does not seem to break anything
				//self.set_size('cr_fade_box_loading', $('#element_width').width(), $('#element_width').height());
			}

			self.element.bind('click', function()
			{
				self.show_fade(show_content);
				return false;
			});

			//setup the event to move the fade box when a window is resized
			$(window).resize(function()
			{
				if($('#' + self.options.id + ' .' + content_class).css('display') != 'none' && $('#' + self.options.id + ' .' + content_class).css('display') != 'none')
				{
		        	self.update_position();
				}
			});

			if(id_is_target)
			{
				self.options.id = self.options.target_fade_box;
			}

			self.set_size('cr_fade_box_loading', 32, 32);
		},

		hide_select: function()
		{
			if($.browser.msie && parseInt($.browser.version) == 6)
			{
				$('select').hide();
				$('#' + this.options.id + ' .cr_fade_box_content select').show();
			}
		},

        show_select: function()
        {
            if($.browser.msie && parseInt($.browser.version) == 6)
            {
                $('select').show();
            }
        },

        show_fade: function(show_content, load_content)
        {
        	var self = this;

        	if(self.options.corners === true)
        	{
        		var top_left_class = 'top_left_' + self.options.color_class;
        		var top_right_class = 'top_right_' + self.options.color_class;
        		var bottom_left_class = 'bottom_left_' + self.options.color_class;
        		var bottom_right_class =  'bottom_right_' + self.options.color_class;

        		if($('#' + self.options.id + ' .cr_fade_box_dim table').length == 0)
        		{
        			$('#' + self.options.id + ' .cr_fade_box_dim').addClass('no_fade');
					$('#' + self.options.id + ' .cr_fade_box_dim').append('<table cellpadding="0" cellspacing="0"><tr><td class="' + top_left_class + '"></td><td class="full_' + self.options.color_class + '"></td><td class="' + top_right_class + '"></td></tr><tr><td class="full_' + self.options.color_class + '"></td><td class="full_' + self.options.color_class + ' middle"></td><td class="full_' + self.options.color_class + '"></td></tr><tr><td class="' + bottom_left_class + '"></td><td class="full_' + self.options.color_class + '"></td><td class="' + bottom_right_class + '"></td></tr></table>');
				}
			}

			if(self.options.fade_click_close === true)
			{
	            $('#' + self.options.id + ' .cr_fade_box_dim').bind('click', function()
	            {
	                self.hide_fade();
	                return false;
	            });
			}
			else
			{
				$('#' + self.options.id + ' .cr_fade_box_dim').unbind('click');
			}

			self.block_ui();

        	//remove all classes and add the correct on if any
			$('#' + self.options.id).removeClass();

			if(self.options.wrapping_class)
			{
				$('#' + self.options.id).addClass(self.options.wrapping_class);
			}

        	if(show_content !== false)
        	{
        		show_content = true;
			}

			if(load_content !== false)
			{
				load_content = true;
			}

			//if the fade is a lock box ajax call then just keep it the current size
			if(self.options.original == true)
			{
            	self.set_fade_size();
			}

            if(self.options.enable_fade === true)
			{
            	$('#' + self.options.id + ' .cr_fade_box_dim').css('display', 'block');
			}

            self.show_content(show_content, load_content);
            self.hide_select();
        	self.disable_scroll();
        },

        block_ui: function()
        {
        	if($('#' + this.options.id + ' .cr_fade_box_block_ui').length == 0 && this.options.block_ui === true)
        	{
        		$('#' + this.options.id).append('<div class="cr_fade_box_block_ui"></div>');
		        var document_height = parseInt($(document).height());
		        var document_width = parseInt($(document).width());

		        $('#' + this.options.id + ' .cr_fade_box_block_ui').css(
		        {
	        		'height': document_height,
	        		'width': document_width
				});
			}
		},

		free_ui: function()
		{
			$('#' + this.options.id + ' .cr_fade_box_block_ui').remove();
		},

        hide_fade: function()
        {
        	this.free_ui();
            this.enable_scroll();
        	this.hide_content();

        	$('#' + this.options.id + ' .cr_fade_box_dim').children('table').remove();
        	$('#' + this.options.id + ' .cr_fade_box_dim').removeClass('no_fade');

            if(this.options.enable_fade === true)
			{
            	$('#' + this.options.id + ' .cr_fade_box_dim').css('display', 'none');
			}

            this.show_select();
            this.hide_loading();
        },

        set_fade_size: function()
        {
        	//alert(this.options.fade_width);
        	//alert(this.options.fade_height);
        	if(this.options.fade_width == null || this.options.fade_height == null)
        	{
	            var fade_height = parseInt($(document).height());
	            var fade_width = parseInt($(document).width());
			}
			else
			{
				fade_height = (this.options.fade_height * 2) + this.options.height;
				fade_width = (this.options.fade_width * 2) + this.options.width;
			}

            this.set_size('cr_fade_box_dim', fade_width, fade_height);
        },

        set_size: function(element_name, element_width, element_height, speed)
        {
			if(element_name == 'cr_fade_box_dim')
			{
				//add to account for the padding on the content box
				element_height += 4;
				element_width += 4;

                if(this.options.corners === true)
        		{
        			/*
        			* This code is mainly for IE6/7 but i am doing it for all browser to keep consistent.  For whatever reason, in IE6/7 i need to specfic the
        			* dimensions for each td middle along with the corners or the corners will not show up.
        			*/
        			$('#' + this.options.id + ' .' + element_name + ' td.middle').css(
        			{
        				height: (element_height - 30),
        				width: (element_width - 30)
					});
				}
			}
			else if(element_name == 'cr_fade_box_content' && this.options.lock_box_auto_resize == true && this.options.original == false)
			{
	            $('#' + this.options.id + ' .' + element_name).css(
            	{
              		height: 'auto',
              		width: 'auto'
				});

				element_height = $('#' + this.options.id + ' .' + element_name).height();

				if($.browser.msie && $.browser.version == 6)
				{
					//element_width = $('#' + this.options.id + ' .' + element_name).width();
				}
			}

        	//generate the correct top and left value
        	var content_top = parseInt((($(window).height() - element_height) / 2));
        	var content_left = parseInt((($(window).width() - element_width) / 2));

            if($.browser.msie && parseInt($.browser.version) == 6)
        	{
        		content_top += $(window).scrollTop();
        		content_left += $(window).scrollLeft();
			}

            $('#' + this.options.id + ' .' + element_name).css(
            {
            	top: content_top,
            	left: content_left,
              	height: element_height,
              	width: element_width
            });

        },

        load_content: function()
        {
            var self = this;
            var id = self.options.url;

            //if(id.substring(0, 5) === 'ajax:')
            if(this.element.hasClass('cr_fade_box_ajax'))
            {
            	var url = id;
            	var data = {};
            	data = $.cr.fn.url_query_to_data(id.split('?')[1]);
				data.fade_box_id = self.options.target_fade_box;

                $.ajax(
                {
                	type: 'get',
                	url: url,
					data: data,
					success: function(message)
					{
						$('#' + self.options.target_fade_box + ' .cr_fade_box_content').css('display', 'none');
						self.show_loading();
						$('#' + self.options.target_fade_box + ' .cr_fade_box_content .cr_content').empty();

						if(self.options.lock_box && self.options.lock_box_auto_resize)
						{
							$('#' + self.options.target_fade_box + ' .cr_fade_box_content').css(
							{
								height: 'auto',
								width: 'auto'
							});

							//for some reason I need to do it this way for IE7 but since it work this way in all browser, just going to do it this way.
							$('body').append('<div id="cr_fade_box_test" style="position: absolute; padding 2px; background:green; top: -10000px; left: -10000px;"><div id="cr_fade_box_test2"></div></div>');
							$('#cr_fade_box_test2').html(message);

							self.options.width = $('#cr_fade_box_test2').width();
							self.options.height = $('#cr_fade_box_test2').height();

							$('#cr_fade_box_test').remove();
						}

						$('#' + self.options.target_fade_box + ' .cr_fade_box_content .cr_content').html(message);

						if(self.options.lock_box && self.options.lock_box_auto_resize)
						{
							$('#' + self.options.target_fade_box + ' .cr_fade_box_content').css('display', 'block');

							if($.browser.version == 7.0 && $.browser.msie)
							{
								self.options.height += $('#' + self.options.target_fade_box + ' .cr_fade_box_title_bar').height();
							}
							else
							{
								self.options.width = $('#' + self.options.target_fade_box + ' .cr_fade_box_content').width();
								self.options.height = $('#' + self.options.target_fade_box + ' .cr_fade_box_content').height();
							}

							//alert(self.options.width + '|' + self.options.height);

							//$('#' + self.options.target_fade_box + ' .cr_fade_box_content').css('display', 'none');
                            self.options.height = (self.options.height > self.options.max_height) ? self.options.max_height : self.options.height;
							self.options.width = (self.options.width > self.options.max_width) ? self.options.max_width : self.options.width;

                            $('#' + self.options.target_fade_box + ' .cr_fade_box_content').css(
							{
								height: 'auto',
								width: self.options.width
							});
						}

            			self.update_title_bar(self.element.attr('title'));
						self.lock_box_update();
						self.hide_loading();
						$('#' + self.options.target_fade_box + ' .cr_fade_box_content').css('display', 'block');
						self.update_position();
					},
					error: function(XMLHttpRequest, textStatus, errorThrown)
					{
						$('#' + self.options.target_fade_box + ' .cr_fade_box_content .cr_content').html('<strong>There was an error retrieving the ajax page.</strong>');
					}
                });
            }
            else
            {
            	//$('#' + self.options.id + ' .cr_fade_box_content .cr_content').append($('#' + id).html());
				//alert("$('#' + " + id + ").clone(true).appendTo('#'" + self.options.id + "' .cr_fade_box_content .cr_content');");
            	//$('#' + id).clone(true).appendTo('#' + self.options.id + ' .cr_fade_box_content .cr_content');

            	//copy the clone content into the object so if they are doing internal links, when we close this fade
            	//box, we will be able to put back the original content into the DOM.
            	$('#' + self.options.target_fade_box + ' .cr_fade_box_content .cr_content').empty();
            	$(self.element).data('cr_fade_box_content').appendTo('#' + self.options.target_fade_box + ' .cr_fade_box_content .cr_content');
            	$('#' + id).removeClass();
            	$('#' + id).show();

            	self.update_title_bar(self.element.attr('title'));
            	self.lock_box_update();
            	self.update_position();
            }

            //self.set_size('cr_fade_box_content', self.options.width, self.options.height);
        },

        lock_box_update: function()
        {
			var self = this;

			if(self.options.lock_box === true && self.options.original === true)
			{
				var options =
				{
					target_fade_box: self.options.target_fade_box,
					lock_box: true,
	        		lock_box_auto_resize: self.options.lock_box_auto_resize,
					show_title: self.options.show_title,
				    max_width: self.options.max_width,
				    max_height: self.options.max_height,
				    link_attribute: 'href',
				    enable_fade: self.options.enable_fade,
				    fade_click_close: self.options.fade_click_close,
				    fade_width: self.options.fade_width,
				    fade_height: self.options.fade_height,
				    auto_scroll: self.options.auto_scroll,
				    corners: self.options.corners,
				    color_class: self.options.color_class,
				    wrapping_class: self.options.wrapping_class,
				    show_title: self.options.show_title,
				    block_ui: self.options.block_ui,
				    original: false,
				    height: self.options.height,
				    width: self.options.width
				};

				$('#' + self.options.target_fade_box + ' .cr_fade_box_content .cr_content a').live('click', function()
				{
					$(this).addClass('cr_fade_box_ajax');
					$(this).fade_box(options);
					$(this).trigger('click');
					return false;
				});
			}
		},

        show_content: function(show_content, load_content)
        {
        	if(load_content === true)
        	{
            	this.load_content();
			}

            if(show_content !== true)
            {
				this.show_loading();
			}
			else
			{
            	$('#' + this.options.id + ' .cr_fade_box_content').show();
            	this.hide_loading();
			}
        },

        hide_content: function()
        {
        	/*if(!this.element.hasClass('cr_fade_box_ajax'))
        	{
            	$('#' + this.options.url).remove();
            	$(this.element).data('cr_fade_box_content').appendTo('body');
            	$('#' + this.options.url).hide();
			}*/

        	$('#' + this.options.target_fade_box + ' .cr_fade_box_content .cr_content').empty();
            $('#' + this.options.id + ' .cr_fade_box_content').hide();
        },

        update_title_bar: function(title)
        {
        	var self = this;

        	if(self.options.show_title === true)
        	{
		        if(title == undefined || title == null || title == '')
		        {
		            title = 'test';
		        }

		        var title_bar = '<div class="cr_fade_box_title_bar" style="width: ' + self.options.width + 'px;"><p>' + title + '<span class="close" style="background: blue;"><a href="#">close</a></span></p></div>';
		        if($('#' + self.options.id + ' .cr_fade_box_title_bar'))
		        {
		            $('#' + self.options.id + ' .cr_fade_box_title_bar').remove();
				}

		        $('#' + self.options.id + ' .cr_fade_box_content').prepend(title_bar);
		        $('#' + self.options.id + ' .cr_fade_box_content span.close a').bind('click', function()
		        {
		            self.hide_fade();
		            return false;
				});
			}
        },

        disable_scroll: function()
        {
        	if($.browser.msie && parseInt($.browser.version) == 6)
        	{
        		$('html').css(
        		{
        			'height': '100%',
        			'overflow': 'hidden'
				});
			}
        },

        enable_scroll: function()
        {
            if($.browser.msie && parseInt($.browser.version) == 6)
        	{
                $('html').css(
        		{
        			'height': '',
        			'overflow': 'auto'
				});
			}
        },

        show_loading: function()
        {
            this.hide_content();
            $('#' + this.options.id + ' .cr_fade_box_loading').css('display', 'block');
		},

		hide_loading: function()
		{
            $('#' + this.options.id + ' .cr_fade_box_loading').css('display', 'none');
		},

        update_data: function(url, show_content)
        {
            this.options.url = url;
            this.show_content(show_content, true);
        },

        update_position: function()
        {
        	this.set_fade_size();
        	this.set_size('cr_fade_box_content', this.options.width, this.options.height);
		}
	});
})(jQuery);